/*
 * @FileName: bsp_comp.c
 * @Author: GreyQiu qiushaogui@aikosolar.com
 * @Date: 2023-07-13 10:46:24
 * @LastEditors: GreyQiu qiushaogui@aikosolar.com
 * @LastEditTime: 2023-09-07 11:34:31
 * @Description: 
 * 
 * Copyright (c) 2023, All Rights Reserved. 
 */

#include "bsp_comp.h"

#define COMP_FILTER_WINDOW  18
#define COMP_FILTER_TH      12

void bsp_comp_init(void)
{
    #if (CMP_VAL_HB1 > 63)
        #error "OVER RADIO"
    #endif
    COMP_InitType COMP_Initial;
    // 使能比较器时钟
    RCC_APB1_Peripheral_Clock_Enable(RCC_APB1_PERIPH_COMP | RCC_APB1_PERIPH_COMP_FILT);

    COMP_Initializes_Structure(&COMP_Initial);

    /* HB1短路 */
    COMP_Initial.InpSel = COMP1_INPSEL_PA0;         // 输入引脚选择
    COMP_Initial.InmSel = COMP1_INMSEL_VREF_VC1;
    COMP_Initial.Hyst = COMP_HYST_LOW;              // 迟滞电压等级，高中低分别对应 40mv 30mv 20mv
    COMP_Initial.PolRev = COMP_OUTPOL_FLIP;         // 输出极性翻转 - 不翻转
    COMP_Initial.SampWindow = COMP_FILTER_WINDOW;   // 采样窗口大小（采样次数）
    COMP_Initial.Threshold  = COMP_FILTER_TH;       // 采样窗口中超过阈值的次数
    COMP_Initial.ClkPsc = 0;
    COMP_Initial.FilterEn = ENABLE;
    COMP_Initial.Blking = COMP_BLANKING_NO;
    COMP_Initial.OutSel = COMP1_OUTSEL_TIM1_BKIN;
    COMP_Initial.En = ENABLE;
    COMP_Initializes(COMP1, &COMP_Initial);

    /* HB2短路 */
    COMP_Initial.InpSel = COMP2_INPSEL_PA3;         // 输入引脚选择
    COMP_Initial.InmSel = COMP2_INMSEL_VREF_VC2;
    COMP_Initial.Hyst = COMP_HYST_LOW;              // 迟滞电压等级，高中低分别对应 40mv 30mv 20mv
    COMP_Initial.PolRev = COMP_OUTPOL_NFLIP;         // 输出极性翻转 - 不翻转
    COMP_Initial.SampWindow = COMP_FILTER_WINDOW;   // 采样窗口大小
    COMP_Initial.Threshold  = COMP_FILTER_TH;
    COMP_Initial.ClkPsc = 0;
    COMP_Initial.FilterEn = ENABLE;
    COMP_Initial.Blking = COMP_BLANKING_NO;
    COMP_Initial.OutSel = COMP2_OUTSEL_TIM1_BKIN;
    COMP_Initial.En = ENABLE;
    COMP_Initializes(COMP2, &COMP_Initial);

    /* 输出过压*/
    COMP_Initial.InpSel = COMP3_INPSEL_PA0;         // 输入引脚选择
    COMP_Initial.InmSel = COMP3_INMSEL_VREF_VC3;
    COMP_Initial.Hyst = COMP_HYST_LOW;              // 迟滞电压等级，高中低分别对应 40mv 30mv 20mv
    COMP_Initial.PolRev = COMP_OUTPOL_NFLIP;         // 输出极性翻转 - 不翻转
    COMP_Initial.SampWindow = COMP_FILTER_WINDOW;   // 采样窗口大小
    COMP_Initial.Threshold  = COMP_FILTER_TH;
    COMP_Initial.FilterEn = ENABLE;
    COMP_Initial.Blking = COMP_BLANKING_TIM1_OC5;
    COMP_Initial.OutSel = COMP3_OUTSEL_TIM1_BKIN;
    COMP_Initial.En = ENABLE;
    COMP_Initializes(COMP3, &COMP_Initial);

    COMP_Voltage_Reference_Config(62, 0, CMP_VAL_HB1, 1, CMP_VAL_HB1, 1);
}


void bsp_comp_enable(void)
{
//    COMP_ON(COMP1);
//    COMP_ON(COMP2);
    // COMP_ON(COMP3);
}

void bsp_comp_disable(void)
{
    COMP_OFF(COMP1);
    COMP_OFF(COMP2);
    // COMP_ON(COMP3);
}
